import navbarTemplate from "./Navbar.html";
import { MessageItem } from "./Message/MessageItem";
import { NotificationItem } from "./Notification/NotificationItem";
import { DomUtils } from "../../utils/DomUtils";
import { userService } from "../../services/userService";

export class Navbar {
  constructor(data = {}) {
    this.data = {
      user: { name: "", avatar: "" },
      messages: [],
      notifications: [],
      unreadMessageCount: 0,
      unreadNotificationCount: 0,
      ...data,
    };
  }

  async loadData() {
    try {
      const user = await userService.getCurrentUser();
      this.data = {
        ...this.data,
        user: {
          name: user.username,
          avatar: user.avatar,
        },
      };
    } catch (error) {
      console.error("加载用户数据失败:", error);
    }
    return this;
  }

  render() {
    // 渲染消息列表
    const messagesHtml = this.data.messages
      .map((item) => new MessageItem(item).render())
      .join("");

    // 渲染通知列表
    const notificationsHtml = this.data.notifications
      .map((item) => new NotificationItem(item).render())
      .join("");

    // 替换模板中的占位符
    const template = navbarTemplate
      .replace(/{{messages}}/g, messagesHtml)
      .replace(/{{notifications}}/g, notificationsHtml)
      .replace(/{{unreadMessageCount}}/g, this.data.unreadMessageCount)
      .replace(
        /{{unreadNotificationCount}}/g,
        this.data.unreadNotificationCount
      )
      .replace(/{{user\.name}}/g, this.data.user.name)
      .replace(/{{user\.avatar}}/g, this.data.user.avatar);

    // 使用 DomUtils 转换为 DOM 元素
    const navbarElement = DomUtils.convertToDom(template);

    // 检查生成的 DOM 元素
    console.log("Navbar Element:", navbarElement);

    return navbarElement;
  }
}
